package org.myapp.page.login.form;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.wicket.Application;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.protocol.http.WebResponse;
import org.myapp.datastore.model.UserModel;

/**
 * サインインフォーム.<br>
 *
 * @author Administrator
 *
 */
public class SigninForm extends BaseForm<LoginFormModel> {

    private static final long serialVersionUID = -3060208671316977405L;

    /**
     * コンストラクタ.<br>
     */
    public SigninForm(LoginFormModel model) {
        super("signinForm", model);

        add(new Button("btnSignin") {

            private static final long serialVersionUID = 1716547079096147174L;

            @Override
            public void onSubmit() {

                LoginFormModel formModel = getFormModel();
                String userId = formModel.getTxtUserId();
                String password = formModel.getTxtPassword1();

            	UserModel model = getLoginService().getUser(userId, password);

            	// ユーザが存在しない
            	if (model == null) {
            		error(this.getLocalizer().getString("msg.error.1", getPage()));
            	} else {
                    // CookieにToken書き出し
                    writeCookie(model);
            	}
            }
        });
    }

    /**
     * トークンをCookieに書込む.<br>
     * @param model ユーザ情報
     */
    private void writeCookie(UserModel model) {

        Cookie cToken = null;

        HttpServletRequest request = ((WebRequest) getRequestCycle().getRequest()).getHttpServletRequest();

        Cookie[] cookies = request.getCookies();

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    cToken = cookie;
                }
            }
        }

        // Cookieが有効な場合は書込まない
        if (cToken != null) {
            return;
        }

        writeToken(model);

        // ログイン日時を更新
        model.setLastLoginDate(new Date());
        model.save();

        info(this.getLocalizer().getString("msg.info.1", getPage()));
    }

    /**
     * Token生成.<br>
     * @param model ユーザ情報
     */
    private void writeToken(UserModel model) {

        byte[] tokens = (model.getUserId() + model.getPassword()).getBytes();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < tokens.length; i++) {
            long token = tokens[i] * (Math.round(Math.random()));
            sb.append(Long.toHexString(token));
        }

        String tokenStr = sb.toString();
        // 使用済Tokenかチェック
        if (getLoginService().isUseToken(tokenStr)) {
            // 使用済なので再帰
            writeToken(model);
        }

        // Responseに書き込み
        HttpServletResponse response = ((WebResponse) getRequestCycle().getResponse()).getHttpServletResponse();
        Cookie token = new Cookie("token", tokenStr);
        token.setMaxAge(60*60*24);

        if (getApplication().getConfigurationType().equals(Application.DEPLOYMENT)) {
            token.setDomain(".appspot.com");
        } else {
            token.setDomain("localhost");
        }

        response.addCookie(token);

        // modelに設定
        model.setToken(tokenStr);
    }
}
